package com.mes.web.controller.cb;

import com.mes.entity.cb.MyTask;
import com.mes.entity.cb.Order;
import com.mes.entity.cb.Pages;
import com.mes.service.cb.OrderService;
import com.mes.utils.CustomUtils;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ResponseUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.activiti.engine.*;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @ClassName: TaskController
 * @Description: 任务管理
 * @Author cb
 * @Date 2018年3月28日16:48:35
 * @version 1.0
 */
@Controller
@RequestMapping("/task")
public class TaskController {


    @Resource
    private TaskService taskService;

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private FormService formService;

    @Resource
    private HistoryService historyService;


    @Resource
    private OrderService orderService;

    @RequestMapping("/daiBan_list")
    public void daiBan_list(String s_name, HttpServletResponse response,String limit,String offset) throws Exception {
        if(s_name==null){
            s_name="";
        }

        List<Task> list=taskService.createTaskQuery() // 创建任务查询
                .taskCandidateOrAssigned("王敏")
                .taskNameLike("%"+s_name+"%") // 根据任务名称查询
                .list(); // 返回带分页的结果集合
        List<MyTask> taskList=new ArrayList<MyTask>();
        for(Task t:list){
            MyTask myTask=new MyTask();
            myTask.setId(t.getId());
            myTask.setName(t.getName());
            myTask.setCreateTime(t.getCreateTime());
            myTask.setProcessInstanceId(t.getProcessInstanceId());
            myTask.setProcessDefinitionId(t.getProcessDefinitionId());
            taskList.add(myTask);
        }
        long total=taskService.createTaskQuery().taskCandidateOrAssigned("王敏").taskNameLike("%"+s_name+"%").count(); // 获取总记录数
        JsonConfig jsonConfig=new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        JSONObject result=new JSONObject();
        JSONArray jsonArray=JSONArray.fromObject(taskList,jsonConfig);
        result.put("rows", jsonArray);
        result.put("total", total);
        ResponseUtil.write(response, result);
    }

    /**
     * 查询当前流程图
     * @param taskId
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/showCurrentView")
    public ModelAndView showCurrentView(String taskId,HttpServletResponse response)throws Exception{
        ModelAndView mav=new ModelAndView();
        Task task=taskService.createTaskQuery() // 创建任务查询
                .taskId(taskId) // 根据任务id查询
                .singleResult();
        String processDefinitionId=task.getProcessDefinitionId(); // 获取流程定义id
        ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery() // 创建流程定义查询
                .processDefinitionId(processDefinitionId) // 根据流程定义id查询
                .singleResult();
        mav.addObject("deploymentId",processDefinition.getDeploymentId()); // 部署id
        mav.addObject("diagramResourceName", processDefinition.getDiagramResourceName()); // 图片资源文件名称

        ProcessDefinitionEntity processDefinitionEntity=(ProcessDefinitionEntity) repositoryService.getProcessDefinition(processDefinitionId);
        String processInstanceId=task.getProcessInstanceId(); // 获取流程实例id
        ProcessInstance pi=runtimeService.createProcessInstanceQuery() // 根据流程实例id获取流程实例
                .processInstanceId(processInstanceId)
                .singleResult();
        ActivityImpl activityImpl=processDefinitionEntity.findActivity(pi.getActivityId()); // 根据活动id获取活动实例
        mav.addObject("x", activityImpl.getX()); // x坐标
        mav.addObject("y", activityImpl.getY()); // y坐标
        mav.addObject("width", activityImpl.getWidth()); // 宽度
        mav.addObject("height", activityImpl.getHeight()); // 高度
        mav.setViewName("cb/currentView");
        return mav;
    }

    /**
     * 重定向审核处理页面
     * @param taskId
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/redirectPage")
    public String redirectPage(String taskId,HttpServletResponse response)throws Exception{

        TaskFormData formData=formService.getTaskFormData(taskId);
        String url=formData.getFormKey();
        JSONObject result=new JSONObject();
        result.put("url", url);
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 经理审核(采购订单)
     * @param oid 订单id
     * @param taskId 任务id
     * @param comments 批注
     * @param state 状态 1--通过 2--不通过
     * @param response
     * @return
     * @throws Exception
     */

    @RequestMapping("/manager")
    public String audit_bz(Long oid,String taskId,String comments,Integer state,HttpServletResponse response)throws Exception{


        JSONObject result = getJsonObject(oid, taskId, comments, state);

        ResponseUtil.write(response, result);

        return null;
    }



    /**
     * 厂长审批
     * @param oid
     * @param taskId
     * @param comments
     * @param state
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/fman")
    public String fman(Long oid,String taskId,String comments,Integer state,HttpServletResponse response)throws Exception{


        JSONObject result = getJsonObject(oid, taskId, comments, state);

        ResponseUtil.write(response, result);

        return null;
    }

    /**
     * 厂长审批
     * @param oid
     * @param taskId
     * @param comments
     * @param state
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/gman")
    public String gman(Long oid,String taskId,String comments,Integer state,HttpServletResponse response)throws Exception{


        JSONObject result = getJsonObject(oid, taskId, comments, state);

        //将"审批中"改为审批通过
        Map<String, Object> map = new HashMap<>();
        map.put("id", oid);
        map.put("state", "2");
        map.put("remark2", null);

        int total = orderService.order_updateByState(map);

        ResponseUtil.write(response, result);

        return null;
    }

    private JSONObject getJsonObject(Long oid, String taskId, String comments, Integer state) {
        Task task=taskService.createTaskQuery() // 创建任务查询
                .taskId(taskId) // 根据任务id查询
                .singleResult();

        JSONObject result=new JSONObject();

        Map<String,Object> variables=new HashMap<>();
        if (null != task) {

            //流程ID
            String processInstanceId = task.getProcessInstanceId();
            if (state == 1) {
                //variables.put("msg", "通过");

            } else {

                //审核未通过,将"审批中"改为审批未通过
                Map<String, Object> map = new HashMap<>();
                map.put("id", oid);
                map.put("state", "3");
                map.put("remark2", processInstanceId);

                int total = orderService.order_updateByState(map);


                //variables.put("msg", "通过");

            }

            // 批注人
            Authentication.setAuthenticatedUserId("12");
            // 添加批注信息
            taskService.addComment(taskId,processInstanceId, comments);
            // 完成审批
            taskService.complete(task.getId(), variables);


            result.put("success", 1);

            } else {
                result.put("success", 2);
            }
        return result;
    }

    /**
     * 已完成任务
     * @param page
     * @param rows
     * @param s_name
     * @param userId
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/yiBan_list")
    public String unFinishedList(int limit,int offset,String s_name,String userId,HttpServletResponse response)throws Exception{
        if(s_name==null){
            s_name="";
        }



        List<HistoricTaskInstance> htiList=historyService.createHistoricTaskInstanceQuery() // 创建历史任务实例查询
                //.taskAssignee(userId) // 根据名称查询
                .taskNameLike("%"+s_name+"%") // 根据任务名称查询
                .orderByTaskCreateTime().asc().finished()
                .listPage(offset,limit);

        long total = historyService.createHistoricTaskInstanceQuery()
                //.taskAssignee(userId) // 根据名称查询
                .taskNameLike("%"+s_name+"%") // 根据任务名称查询
                .finished()
                .count();

        List<MyTask> taskList=new ArrayList<>();
        if (htiList.size()>0) {
            for(HistoricTaskInstance hti:htiList){
                MyTask myTask=new MyTask();
                myTask.setId(hti.getId());
                myTask.setName(hti.getName());
                myTask.setCreateTime(hti.getCreateTime());
                myTask.setEndTime(hti.getEndTime());
                taskList.add(myTask);
            }
        }

        JsonConfig jsonConfig=new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        JSONObject result=new JSONObject();
        JSONArray jsonArray=JSONArray.fromObject(taskList,jsonConfig);
        result.put("rows", jsonArray);
        result.put("total", total);
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 根据任务id查询流程实例的具体执行过程
     * @param taskId
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/listAction")
    public String listAction(String taskId,HttpServletResponse response)throws Exception{
        if (null == taskId) {
            return null;
        }
        HistoricTaskInstance hti=historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        if (null != hti) {
            String processInstanceId=hti.getProcessInstanceId(); // 获取流程实例id
            List<HistoricActivityInstance> haiList=historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();

            JsonConfig jsonConfig=new JsonConfig();
            jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
            JSONObject result=new JSONObject();
            JSONArray jsonArray=JSONArray.fromObject(haiList,jsonConfig);
            result.put("rows", jsonArray);
            ResponseUtil.write(response, result);
        }
        return null;
    }

    /**
     * 历史批注 通过流程实例id查询
     * @param processInstanceId
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/listHistoryCommentWithProcessInstanceId")
    public String listHistoryCommentWithProcessInstanceId(String processInstanceId,HttpServletResponse response)throws Exception{
        if(processInstanceId==null){
            return null;
        }
        List<Comment> commentList=taskService.getProcessInstanceComments(processInstanceId);
        Collections.reverse(commentList); // 集合元素反转
        JsonConfig jsonConfig=new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        JSONObject result=new JSONObject();
        JSONArray jsonArray=JSONArray.fromObject(commentList,jsonConfig);
        result.put("rows", jsonArray);
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 查看流程图
     * @param
     * @param
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/showViewByTaskId")
    public String showViewByTaskId(String taskId,HttpServletResponse response)throws Exception{
        HistoricTaskInstance hti=historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        String processDefinitionId=hti.getProcessDefinitionId(); // 获取流程定义id
        ProcessDefinition pd=repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        InputStream inputStream=repositoryService.getResourceAsStream(pd.getDeploymentId(), pd.getDiagramResourceName());
        OutputStream out=response.getOutputStream();
        for(int b=-1;(b=inputStream.read())!=-1;){
            out.write(b);
        }
        out.close();
        inputStream.close();
        return null;
    }


    /**
     * 历史批注查询 根据任务id
     * @param taskId
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/listHistoryComment")
    public String listHistoryComment(String taskId,HttpServletResponse response,HttpServletRequest request)throws Exception{
        if(taskId==null){
            return null;
        }


        HistoricTaskInstance hti=historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        List<Comment> commentList=taskService.getProcessInstanceComments(hti.getProcessInstanceId());


        Collections.reverse(commentList); // 集合元素反转
        JsonConfig jsonConfig=new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        JSONObject result=new JSONObject();
        JSONArray jsonArray=JSONArray.fromObject(commentList,jsonConfig);
        result.put("rows", jsonArray);
        ResponseUtil.write(response, result);
        return null;
    }

}
